package me.jiatao.paging3.paging3.mediator

import androidx.paging.*
import androidx.room.withTransaction
import kotlinx.coroutines.delay
import me.jiatao.paging3.MyApplication
import me.jiatao.paging3.room.ArticleEntity
import me.jiatao.paging3.room.remotekeys.RemoteKeysEntity


@OptIn(ExperimentalPagingApi::class)
class ProjectRemoteMediator : RemoteMediator<Int, ArticleEntity>() {
    //    override suspend fun initialize(): InitializeAction {
//        // Require that remote REFRESH is launched on initial load and succeeds before launching
//        // remote PREPEND / APPEND.
//        return InitializeAction.LAUNCH_INITIAL_REFRESH
//    }
    private val remoteKeysDao = MyApplication.getDB().remoteKeysDao()
    private val articleDao = MyApplication.getDB().articleDao()


    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, ArticleEntity>
    ): MediatorResult {


        val pageKey = when (loadType) {
            LoadType.REFRESH -> null

            LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)

            LoadType.APPEND -> {
                val lastItem = state.lastItemOrNull()

                if (lastItem == null) {
                    return MediatorResult.Success(true)
                }

                lastItem.id
            }
        }


        delay(2000)

        val page = pageKey ?: 0

        val entityList = List(30) { index ->
            ArticleEntity(
                dbID = null,
                id = page + index,
                title = " title ${page + index}",
                desc = " desc ${page + index}",
                link = " link ${page + index}",
                pic = " pic ${page + index}"
            )
        }


        MyApplication.getDB().withTransaction {
            val entity = RemoteKeysEntity(
                remoteName = "pokemon",
                nextKey = page + 1
            )
            remoteKeysDao.insertAll(entity)
            articleDao.insertAll(entityList)
        }


        return MediatorResult.Success(false)

//        /**
//         * 执行网络请求
//         */
//        val page = pageKey ?: 1
//        println("page---->$page")


//        val projectResult = apiCall {
//            RetrofitClient.wanAndroidApi.getProjectList(page)
//        }
//
//
//
//        if (projectResult.code == HttpConst.CODE_SUCCESS) {
//            projectResult.data?.let { projectData ->
//                projectData.datas?.let { articleList ->
//
////                    return withContext(Dispatchers.IO) {
////                        val entityList = articleList.map { articleItem ->
////                            articleItem2ArticleEntity(articleItem)
////                        }
////                        println(entityList.size)
////                        MyApplication.getDB().articleDao().insertAll(entityList)
////                        println("1111111111111111111")
////                        return@withContext MediatorResult.Success(endOfPaginationReached = true)
////                    }
//
//                    val entityList = articleList.map { articleItem ->
//                        articleItem2ArticleEntity(articleItem)
//                    }
//                    println(entityList.size)
//                    MyApplication.getDB().articleDao().insertAll(entityList)
//                    println("1111111111111111111")
//                    return MediatorResult.Success(endOfPaginationReached = true)
//                }
//            }
//
//
//            println("22222222222222222")
//            return MediatorResult.Success(endOfPaginationReached = true)
//        } else {
//            return MediatorResult.Error(Exception("code error"))
//        }
    }
}